<template>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    :http-request="uploadFunc"
    multiple
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :limit="1"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
  >
    <el-button type="primary">导入</el-button>
    <template #tip>
      <div class="el-upload__tip">可传文件类型：xls/xlsx/csv， files with a size less than 5M.</div>
    </template>
  </el-upload>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import type { UploadProps, UploadUserFile } from 'element-plus'
import { uploadUserListRequest } from '@/service/system/system.ts'

const uploadAction = import.meta.env.VITE_BASE_URL_DEV + 'api/pub/imp-any'

const fileList = ref<UploadUserFile[]>([])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 1, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`,
  )
}

function beforeUpload(file) {
  const isSize = new Promise(function (resolve, reject) {
    let _URL = window.URL || window.webkitURL
    let image = new Image()
    console.log('file-=-=-=-=-=')
    console.log(file)

    image.src = _URL.createObjectURL(file)
  }).then()

  // 文件大小 单位：kb
  if (file.size > 5120) {
    ElMessage.error('上传文大于5M!')
    return false
  }

  let fileName = file.name.split('.')
  let nameTypeLen = fileName.length
  let fileType = fileName[nameTypeLen - 1]
  console.log('fileType   -=-=-=-=-=')

  console.log(fileType)

  if (fileType !== 'xls' && fileType !== 'xlsx' && fileType !== 'csv') {
    ElMessage.error('上传头像图片只能是 xls、xlsx、csv 格式!')
    return false
  }
}

// 自定义上传
function uploadFunc(file: any) {
  console.log('自定义上传   -=-=-=-=-=')
  console.log(file)
  // 创建 FormData 对象
  const formData: any = new FormData()
  // 将文件添加到 FormData 中
  formData.append('file', file?.file)

  uploadUserListRequest(formData).then((res) => {
    if (res.code == 200) {
      ElMessage.success('上传成功')
    }
  })
}

function uploadError(err, file, fileList) {
  ElMessage.error('上传出错，请刷新页面！')
  console.log(err)
}
</script>
